using Unity.Burst;
using Unity.Collections;
using Unity.Entities;
using UnityEngine;

namespace HelloCube.GameObjectSync
{
    [UpdateInGroup(typeof(InitializationSystemGroup))]
    public partial struct RotationInitSystem : ISystem
    {
        [BurstCompile]
        public void OnCreate(ref SystemState state)
        {
            state.RequireForUpdate<Execute.GameObjectSync>();
            state.RequireForUpdate<DirectoryManaged>();
        }

        //方法内部使用了托管对象时不可使用 BurstCompile
        public void OnUpdate(ref SystemState state)
        {
            var directoryManaged = SystemAPI.ManagedAPI.GetSingleton<DirectoryManaged>();
            var ecb = new EntityCommandBuffer(Allocator.Temp);

            foreach (var (goPrefab, entity) in SystemAPI.Query<RotateSpeed>().WithNone<RotatorGO>().WithEntityAccess())
            {
                var go = GameObject.Instantiate(directoryManaged.RotatorPrefab);
                //迭代实体时不可添加组件，所以使用 ecb 来添加组件
                ecb.AddComponent(entity, new RotatorGO(go));
            }

            ecb.Playback(state.EntityManager);
        }
    }

    public class RotatorGO : IComponentData
    {
        public GameObject Value;

        public RotatorGO(GameObject value)
        {
            Value = value;
        }
        
        //托管类型的 组件 必须有一个无参的构造函数，否则报错
        public RotatorGO(){}
    }
}